use bevy::prelude::*;
use crate::{WORLD_WIDTH, WORLD_HEIGHT, TANK_SPEED, TANK_SIZE};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
    pub x: i32,
    pub y: i32,
}

// 将Tank属性拆分为多个组件
#[derive(Component, Debug)]
pub struct Tank {
    pub id: usize,
    pub alive: bool,
    pub location: Location,
    pub velocity: Velocity,
    // 添加消息存储字段
    pub messages: Vec<String>,
    // 添加团队ID字段
    pub team_id: usize,
}

impl Tank {
    /// 移动坦克并处理边界碰撞
    pub fn move_tank(&mut self) {
        if !self.alive {
            return;
        }

        // 更新位置
        let mut new_x = self.location.x + self.velocity.x;
        let mut new_y = self.location.y + self.velocity.y;

        // 边界检测和反弹
        if new_x <= 0.0 || new_x >= WORLD_WIDTH {
            self.velocity.x *= -1.0;
            new_x = self.location.x; // 保持在边界内
            trace!("Tank {} bounced on X axis", self.id);
        }

        if new_y <= 0.0 || new_y >= WORLD_HEIGHT {
            self.velocity.y *= -1.0;
            new_y = self.location.y; // 保持在边界内
            trace!("Tank {} bounced on Y axis", self.id);
        }

        self.location.x = new_x;
        self.location.y = new_y;

        trace!(
            "Tank {} moved to ({}, {})",
            self.id, self.location.x, self.location.y
        );
    }

    // 1. 发现目标方法
    pub fn detect_targets(&self, other_tanks: &[&Tank]) -> Vec<usize> {
        let mut targets = Vec::new();
        for tank in other_tanks {
            if tank.alive && tank.team_id != self.team_id {
                // 简单的距离检测，这里假设在同一网格的坦克即为可检测到的
                let distance = ((self.location.x - tank.location.x).powi(2)
                    + (self.location.y - tank.location.y).powi(2))
                .sqrt();
                // 假设检测范围为TANK_SIZE的5倍
                if distance <= TANK_SIZE * 5.0 {
                    targets.push(tank.id);
                }
            }
        }
        targets
    }

    // 2. 发送击毁消息方法
    pub fn send_destroy_message(&self, target_id: usize) -> String {
        format!("DESTROY_TANK_{}", target_id)
    }

    // 3. 接收击毁消息方法
    pub fn receive_destroy_message(&mut self, message: String) {
        self.messages.push(message);
    }

    // 4. 摧毁自己方法
    pub fn destroy_self(&mut self) {
        self.alive = false;
        self.messages.push("DESTROYED".to_string());
    }
}

/// Velocity组件结构体，用于表示物体在二维空间中的速度矢量
///
/// 该结构体通常作为ECS架构中的组件使用，存储物体在x轴和y轴方向上的速度分量
///
/// # 字段说明
/// * `x` - x轴方向的速度分量，类型为f32
/// * `y` - y轴方向的速度分量，类型为f32
#[derive(Component, Debug)]
pub struct Velocity {
    pub x: f32,
    pub y: f32,
}

/// Location组件结构体，用于表示游戏中的位置信息
///
/// 该结构体包含x和y两个f32类型的坐标值，用于存储实体在二维空间中的位置
/// x: f32 - X轴坐标值
/// y: f32 - Y轴坐标值
#[derive(Component, Debug)]
pub struct Location {
    pub x: f32,
    pub y: f32,
}